/* 
 * File:   CellsCreator.cpp
 * Author: Guilherme Monteiro
 * 
 */

#include "../headers/CellsCreator.h"

/**
 * Constructor of CellsCreator class
 * 
 * @param vLines: vertical lines
 * @param hLines: horizontal lines
 */
CellsCreator::CellsCreator(vector<Line> vLines, vector<Line> hLines) {
    this->verticalLines = vLines;
    this->horizontalLines = hLines;
}

CellsCreator::CellsCreator(const CellsCreator& orig) {
}

CellsCreator::~CellsCreator() {
}

/**
 * Returns a vector of cells
 * formed from the two vector of lines
 * passed in contructor.
 * 
 * @return vector of cells
 */
vector<Cell> CellsCreator::createCells() {
    vector<Cell> cellsVector;

    vector<Line>::iterator horizontalIt, verticalIt;
    
    for(horizontalIt = horizontalLines.begin(); horizontalIt != horizontalLines.end();) {
        Line line1 = *horizontalIt;
        Line line2 = *(++horizontalIt);
        
        for(verticalIt = verticalLines.begin(); verticalIt != --verticalLines.end();) {
        
            Line line3 = *verticalIt;
            Line line4 = *(++verticalIt);
            
//            printf("h line 1: (%d,%d) - (%d,%d)\n", line1.p1.x, line1.p1.y, line1.p2.x, line1.p2.y);
//            printf("h line 2: (%d,%d) - (%d,%d)\n", line2.p1.x, line2.p1.y, line2.p2.x, line2.p2.y);
//            printf("v line 3: (%d,%d) - (%d,%d)\n", line3.p1.x, line3.p1.y, line3.p2.x, line3.p2.y);
//            printf("v line 4: (%d,%d) - (%d,%d)\n", line4.p1.x, line4.p1.y, line4.p2.x, line4.p2.y);
            
            CvPoint c1 = line1.intersection(line3);
            CvPoint c2 = line2.intersection(line4);

            if(!(c1.x == -1 || c1.y == -1 || c2.x == -1 || c2.y == -1)) {
//                printf("--> c1: (%d,%d) c2:(%d,%d)\n", c1.x, c1.y, c2.x, c2.y);
                Cell* c = new Cell(c1, c2);
                if((*c).isValid()) {
                    cellsVector.push_back(*c);
                }
            }
        }
    }
    return cellsVector;
}

